#!/usr/local/bin/python2.7

import writer, os, string
from constants import *
from collections import OrderedDict

class DelimWriter(object):

    def __init__(self, delimiter = '$'):
        self._delim = delimiter
        self._dst_dir = Constants.logs_dir
        self._name = 'mycmdb'
        self._extension = 'txt'

        self._text = ''
        self._components = []
        
        self._dict_keys = OrderedDict()
        self._dict_keys['gen'] = ['SystemName', 'SystemNumber', \
            'UniqueIDNumber', 'ItemName', 'BuildingNumber', 'Location', \
            'Drawings', 'CriticalComponent', 'AdditionalIdentifiers', 'Comments']
        self._dict_keys['mech'] = ['To', 'From', 'Manufacturer', \
            'ModelNumber', 'SerialNumber', 'Size', 'FlowRates', 'RPM', \
            'Material']
        self._dict_keys['elec'] = ['To', 'From', 'Manufacturer', \
            'ModelNumber', 'SerialNumber', 'HorsePower', 'RPM', 'Volts', \
            'Hertz', 'Phase', 'Amps']
        self._dict_keys['iandc'] = ['To', 'From', 'Manufacturer', \
            'ModelNumber', 'SerialNumber', 'OutputRange', 'DisplayRange', \
            'Medium', 'AnalogorDigital']

    def saveFile(self):
        self._reset()
        self._buildHeader()
        self._buildText()
        self._writeIntoFile()

    def addComponent(self, comp):
        self._components.append(comps)
    def addComponents(self, comps):
        self._components.extend(comps)

    def _reset(self):
        self._text = ''

    def _buildHeader(self):
        line = ''
        cat_delimiter = ': '

        for field in self._dict_keys['gen']:
            line += 'General'
            line += cat_delimiter
            line += field
            line += self._delim
        for field in self._dict_keys['mech']:
            line += 'Mechanical'
            line += cat_delimiter
            line += field
            line += self._delim
        for field in self._dict_keys['elec']:
            line += 'Electrical'
            line += cat_delimiter
            line += field
            line += self._delim
        for field in self._dict_keys['iandc']:
            line += 'Instrumentation and Control'
            line += cat_delimiter
            line += field
            line += self._delim

        line += 'Pic path'
        line += self._delim
        line += 'Pic name'
        line += '\n'

        self._text += line

    def _buildText(self):
        n_comps = len(self._components) * 1.0
        i = 0.0
        last = 0
        for comp in self._components:
            self._buildComp(comp)

            perc = round(i / n_comps * 100, 0)
            if perc != last:
                print str(perc) + '% done...'
                last = perc
            i += 1

    def _buildComp(self, comp):
        val_delim = ', '
        prop_dicts = ['gen', 'mech', 'elec', 'iandc']
        row = ''

        for dict_name in prop_dicts:
            for field_name in self._dict_keys[dict_name]:
                vals = comp.getValue(dict_name, field_name)
                for val in vals:
                    row += str(val.strip()) + val_delim
                if len(vals) > 0:
                    row = row[:-(len(val_delim))]
                row += self._delim

        row += self._makePics(comp)

        self._text += row + '\n'

        if len(self._text) > 5000000:
            self._writeIntoFile()

    def _makePics(self, comp):
        pics = comp.getPics()
        if len(pics) == 0:
            return ''

        #pic_delim = ', '
        pic_delim = ';'
        pic_text = ''

        pic_text += pics[0].path
        pic_text += self._delim

        for pic in pics:
            pic_text += pic.name
            pic_text += pic_delim

        pic_text = pic_text[:-(len(pic_delim))]
        return pic_text

    def _writeIntoFile(self):
        name = self._name + '.' + self._extension
        dst = os.path.join(self._dst_dir, name)

        if not os.path.exists(dst):
            with open(dst, 'w') as myfile:
                myfile.write(self._text)
        else:
            with open(dst, 'a') as myfile:
                myfile.write(self._text)

            self._text = ''

